#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from django import newforms as forms
from django.utils.translation import gettext_lazy as _

from models import Profile

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ('user', 'report_to',)


class UserForm(forms.Form):
    login_name = forms.CharField(max_length=30, min_length=4)
    email = forms.EmailField()
    password = forms.CharField(max_length=12, min_length=6, widget=forms.PasswordInput)
    repassword = forms.CharField(max_length=12, min_length=6,
            widget=forms.PasswordInput)

    def clean_login_name(self):
        """
        Verify that the username isn't already registered
        """
        username = self.cleaned_data.get("login_name")
        if not set(username).issubset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_."):
            raise forms.ValidationError(_("That login name has invalid characters. The valid values are letters, numbers and underscore."))

        if User.objects.filter(username__iexact=username).count() == 0:
            return username
        else:
            raise forms.ValidationError(_("The login name is already registered."))

    def clean(self):
        """
        Verify that the 2 passwords fields are equal
        """
        if self.cleaned_data.get("password") == self.cleaned_data.get("repassword"):
            return self.cleaned_data
        else:
            raise forms.ValidationError(_("The passwords inserted are different."))

    def clean_email(self):
        """
        Verify that the email exists
        """
        email = self.cleaned_data.get("email")

        try:
            User.objects.get(email=email)
        except:
            return email

        raise forms.ValidationError(_("That e-mail is already used."))
